package com.xtt.demo.controller;

import com.xtt.common.Exception.AppException;
import com.xtt.common.entity.JsonResult;
import com.xtt.demo.model.User;
import com.xtt.demo.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author xtt.
 * @Description:
 * @Date:Create in 2017/5/29 0029 下午 15:54
 * @Modify By:
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{


    @Autowired
    private IUserService service;

    @GetMapping("/findAll")
    public JsonResult findAll() {
        List<User> users = service.findAll();
        return renderSuccess(users);
    }

    @GetMapping("/findByName")
    public JsonResult findByName(String name) {
        List<User> users = service.findByName("zhangsan");
        return renderSuccess(users);
    }

    /**
     * 事务测试
     */
    @GetMapping("/insert1")
    public void insert() throws AppException {
        service.insert();
    }

    /**
     * 校验测试/日期转换
     * @param user
     * @param result
     * @return
     */
    @GetMapping("/insertUser")
    public JsonResult insertUser(@Valid User user, BindingResult result) {
        if(result.hasErrors()) {
            return renderError(result.getFieldError().getDefaultMessage());
        }
        service.insert(user);
        return renderSuccess("success");
    }

    /**
     * aop 使用测试
     * @return
     */
    @GetMapping("/testAop")
    public void testAop(){
        service.testAop();
    }

    /**
     * 全局异常测试
     * @return
     * @throws AppException
     */
    @GetMapping("/testException")
    public JsonResult testException() throws Exception {
        User user = service.testExceptionHandle();
        return renderSuccess(user);
    }
}
